package com.dy.lock.screen.component.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.ScoreInfoComponent;
import com.dy.lock.screen.constants.Constant;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.pojo.AdvertOperatorInfo;
import com.dy.lock.screen.pojo.ScoreInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.AdvertOperatorService;
import com.dy.lock.screen.service.ScoreService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.utils.DateUtil;
import com.dy.lock.screen.vo.EverydayToday;
import com.dy.lock.screen.vo.ScoreVo;
import com.google.gson.Gson;

@Component("scoreInfoComponent")
public class ScoreInfoComponentImpl implements ScoreInfoComponent {
	private static final Logger log = Logger
			.getLogger(ScoreInfoComponentImpl.class);
	private Gson gson;

	@Resource(name = "scoreService")
	private ScoreService scoreService;
	@Resource(name = "advertOperatorService")
	private AdvertOperatorService advertOperatorService;

	public ScoreInfoComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public ScoreVo getExchangedScore(String body, Head head) {
		ScoreVo vo = gson.fromJson(body, ScoreVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getUserId())) {
			ScoreInfo info = new ScoreInfo();
			info.setCustomerId(vo.getUserId());
			ScoreInfo re = this.scoreService.getExchangedScore(info);
			if (re != null) {
				vo.setGold(re.getExchangedScore());
				vo.setTotalLeftSlide(re.getLeftSlideScore());
				vo.setTotalRightSlide(re.getRightSlideScore());
				vo.setTotalLockscreen(CommonUtil.add(vo.getLeftSlide(), vo
						.getRightSlide()));
				return vo;
			} else {
				vo.setGold(0);
				return vo;
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取剩余逗币时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public List<ScoreVo> getBills(String body, Head head) {
		ScoreVo vo = gson.fromJson(body, ScoreVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getUserId())) {
			List<ScoreVo> returnList = new ArrayList<ScoreVo>();
			List<ScoreInfo> queryPayBills = this.scoreService.queryPayBills(vo
					.getUserId());
			List<ScoreInfo> queryIncomeBills = this.scoreService
					.queryIncomeBills(vo.getUserId());
			List<ScoreInfo> allList = new ArrayList<ScoreInfo>();
			if (queryPayBills != null && !queryPayBills.isEmpty()) {
				allList.addAll(queryPayBills);
			}

			for (int i = 0; null != queryIncomeBills
					&& i < queryIncomeBills.size(); i++) {
				ScoreInfo info = queryIncomeBills.get(i);
				int index = allList.indexOf(info);
				if (index >= 0) {
					allList.get(index).setTotalIncome(info.getTotalIncome());
				} else {
					allList.add(info);
				}
			}

			for (int i = 0; null != allList && i < allList.size(); i++) {
				ScoreInfo scoreInfo = allList.get(i);
				ScoreVo scoreVo = new ScoreVo();
				scoreVo.setUserId(scoreInfo.getCustomerId());
				scoreVo.setMonth(scoreInfo.getMonth());
				// if (queryPayBills.size() >= queryIncomeBills.size()
				// && scoreInfo.getMonth().equals(
				// queryIncomeBills.get(i).getMonth())) {
				// scoreVo.setTotalIncome(queryIncomeBills.get(i)
				// .getTotalIncome());
				// } else {
				// scoreVo.setTotalIncome(0);
				// }
				scoreVo.setTotalPay(scoreInfo.getTotalPay());
				scoreVo.setTotalIncome(scoreInfo.getTotalIncome());
				// 收入
				List<EverydayToday> everydayIncome = this.scoreService
						.queryIncomeBillDetail(scoreInfo.getCustomerId(),
								scoreInfo.getMonth());
				// 支出
				List<EverydayToday> everydayPay = this.scoreService
						.queryPayBillDetail(scoreInfo.getCustomerId(),
								scoreInfo.getMonth());
				scoreVo.setEverydayIncome(everydayIncome);
				scoreVo.setEverydayPay(everydayPay);
				returnList.add(scoreVo);
			}
			if (returnList.size() > 0) {
				return returnList;
			} else {
				throw new ServerDisponseException(TransmissionCode.NO_DATA
						.getCode(), TransmissionCode.NO_DATA.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取账单时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public ScoreVo getTodayScore(String body, Head head) {
		ScoreVo vo = gson.fromJson(body, ScoreVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getUserId())) {
			AdvertOperatorInfo opt = new AdvertOperatorInfo();
			opt.setUserId(vo.getUserId());
			opt.setOperatorTime(new Date());
			List<AdvertOperatorInfo> list = this.advertOperatorService
					.queryByCustomerId(opt);
			Integer todayTotal = 0;
			Integer todaySignInScore = 0;
			Integer todayInvitationScore = 0;
			Integer todayRightSlideScore = 0;
			Integer todayLeftSlideScore = 0;
			if (list != null && !list.isEmpty()) {
				for (AdvertOperatorInfo aopt : list) {
					String optType = aopt.getOperatorType();
					Integer score = aopt.getAdScore();
					if (score == null) {
						score = 0;
					}
					if (Constant.ADVERT_OPERATE_LEFT.equals(optType)
							|| Constant.ADVERT_OPERATE_RIGHT.equals(optType)
							|| Constant.ADVERT_OPERATE_SIGN_IN.equals(optType)
							|| Constant.ADVERT_OPERATE_INVITE.equals(optType)) {
						todayTotal += score;
					}
					if (Constant.ADVERT_OPERATE_LEFT.equals(optType)) {
						todayLeftSlideScore += score;
					} else if (Constant.ADVERT_OPERATE_RIGHT.equals(optType)) {
						todayRightSlideScore += score;
					} else if (Constant.ADVERT_OPERATE_SIGN_IN.equals(optType)) {
						todaySignInScore += score;
					} else if (Constant.ADVERT_OPERATE_INVITE.equals(optType)) {
						todayInvitationScore += score;
					}
				}
				vo.setTodayGold(todayTotal);
				vo.setDailyAttendance(todaySignInScore);
				vo.setInvitation(todayInvitationScore);
				vo.setRightSlide(todayRightSlideScore);
				vo.setLeftSlide(todayLeftSlideScore);
				vo.setTotalLockscreen(CommonUtil.add(todayLeftSlideScore,
						todayRightSlideScore));
				return vo;
			} else {
				throw new ServerDisponseException(TransmissionCode.NO_DATA
						.getCode(), TransmissionCode.NO_DATA.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取今日数据时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public synchronized ScoreVo customerSignIn(String body, Head head) {
		ScoreVo vo = gson.fromJson(body, ScoreVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getUserId())) {
			ScoreVo signInfo = this.querySignIn(body, head);
			if (signInfo != null && signInfo.isSign()) {
				ScoreVo sVo = new ScoreVo();
				sVo.setAttendance(true);
				return sVo;
			}
			ScoreInfo info = new ScoreInfo();
			info.setCustomerId(vo.getUserId());
			// 签到时间
			info.setSignInDate(new Date());
			ScoreInfo scInfo = this.scoreService.queryByPrimaryKey(vo
					.getUserId());
			int signRe = -1;
			if (scInfo == null) {
				// 签到积分 暂时30分
				info.setSignInScore(Constant.SIGN_IN_SCORE);
				info.setInsertTime(new Date());
				info.setTotalScore(Constant.SIGN_IN_SCORE);
				info.setExchangedScore(Constant.SIGN_IN_SCORE);
				signRe = this.scoreService.save(info);
			} else {
				info.setSignInScore(CommonUtil.add(scInfo.getSignInScore(),
						Constant.SIGN_IN_SCORE));
				info.setUpdateTime(new Date());
				info.setTotalScore(CommonUtil.add(scInfo.getTotalScore(),
						Constant.SIGN_IN_SCORE));
				info.setExchangedScore(CommonUtil.add(scInfo
						.getExchangedScore(), Constant.SIGN_IN_SCORE));
				signRe = this.scoreService.updateScore(info);
			}
			if (signRe >= 0) {
				AdvertOperatorInfo adOpt = new AdvertOperatorInfo();
				adOpt.setUserId(vo.getUserId());
				adOpt.setAdScore(Constant.SIGN_IN_SCORE);
				adOpt.setOperatorType(Constant.ADVERT_OPERATE_SIGN_IN);
				this.advertOperatorService.save(adOpt, head);
				ScoreVo sVo = new ScoreVo();
				sVo.setAttendance(true);
				return sVo;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",客户签到时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public ScoreVo querySignIn(String body, Head head) {
		ScoreVo vo = gson.fromJson(body, ScoreVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getUserId())) {
			ScoreInfo info = new ScoreInfo();
			info.setCustomerId(vo.getUserId());
			ScoreInfo scInfo = this.scoreService.queryByPrimaryKey(vo
					.getUserId());
			ScoreVo sVo = new ScoreVo();
			if (scInfo != null) {
				Date signInDate = scInfo.getSignInDate();
				Date nowDate = new Date();
				if (signInDate == null) {
					sVo.setSign(false);
					return sVo;
				} else {
					String signInDateStr = DateUtil.format(signInDate);
					String nowDateStr = DateUtil.format(nowDate);
					if (signInDateStr.equals(nowDateStr)) {
						sVo.setSign(true);
						return sVo;
					} else {
						sVo.setSign(false);
						return sVo;
					}
				}
			} else {
				sVo.setSign(false);
				return sVo;
			}

		} else {
			log.info("requestId:" + head.getRequestId() + ",查询客户签到时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

}
